package Z.dailyExercise.March;

import java.util.*;

public class _347前K个高频元素 {
    /**
     * 直接遍历 借助hashmap存
     * @param nums
     * @param k
     * @return
     */
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int num:nums) {
            map.put(num,map.getOrDefault(num,0)+1);

        }

        List<Map .Entry<Integer,Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue()-o1.getValue();
            }
        });

        int[] res = new int[k];
        for (int i=0;i<k;i++){
            res[i] = list.get(i).getKey();
        }
        return res;



    }
}
